package com.qd.system.importexcel.personrole;

import com.cdqidi.dto.ApiResult;
import com.cdqidi.dto.ApiResultWrapper;
import com.cdqidi.dto.BatchResult;
import com.cdqidi.excel.domain.ExcelRowMsg;
import com.cdqidi.excel.domain.ImportErr;
import com.cdqidi.excel.handle.ExcelImportIProcessor;
import com.cdqidi.excel.util.ExcelUtil;
import com.cdqidi.util.ValidatorUtil;
import com.cdqidi.util.page.PageUtil;
import com.qd.common.sys.domain.entity.person.PersonRoleDTO;
import com.qd.system.service.person.PersonRoleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 用户和角色,excel导入入口类
 *
 * @author sjk
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class PersonRoleImport implements ExcelImportIProcessor<PersonRoleDTO> {

    private final ValidatorUtil validatorUtil;
    private final PersonRoleService personRoleService;

    /**
     * 资源名字，默认为处理导入导出实体的全路径，比如：xx.xx.xxDto
     *
     * @return 资源名字
     */
    @Override
    public String getResourceName() {
        return PersonRoleDTO.class.getCanonicalName();
    }

    /**
     * excel行数据重复验证，返回需要验证的字段以及说明 比如map.put("account","账号"),表示excel 中的行数据账号不能重复
     *
     * @return 返回需要验证的字段map
     */
    @Override
    public Map<String, String> repeatedColumns() {
        return ExcelImportIProcessor.super.repeatedColumns();
    }

    /**
     * 所有excel表格数据
     * 不需要加@Transactional，接口中已经添加
     *
     * @param rowList   excel列表信息
     * @param errorList 异常信息
     */
    @Override
    public ApiResultWrapper<Object> importExcel(List<ExcelRowMsg<PersonRoleDTO>> rowList, List<ImportErr> errorList) {
        final int size = rowList.size();
        final List<BatchResult> results = ExcelUtil.buildBatchResult(0, 0);
        final PersonRoleImportHandler personRoleImportHandler = new PersonRoleImportHandler(personRoleService, validatorUtil, errorList);
        for (int i = 1; i <= PageUtil.getNumber(size); i++) {
            final List<ExcelRowMsg<PersonRoleDTO>> subList = PageUtil.page(rowList, size, i);
            if (!subList.isEmpty()) {
                personRoleImportHandler.process(subList, results);
            }
        }
        return ApiResult.success(results);
    }
}